package com.zzyl.nursing.service.impl;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;

import cn.hutool.json.JSON;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.zzyl.common.exception.base.BaseException;
import com.zzyl.common.utils.DateUtils;
import com.zzyl.nursing.domain.*;
import com.zzyl.nursing.dto.CheckInApplyDto;
import com.zzyl.nursing.dto.CheckInConfigDto;
import com.zzyl.nursing.dto.ElderFamilyDto;
import com.zzyl.nursing.mapper.CheckInConfigMapper;
import com.zzyl.nursing.mapper.ContractMapper;
import com.zzyl.nursing.service.*;
import com.zzyl.nursing.util.CodeGenerator;
import com.zzyl.nursing.vo.CheckInConfigVo;
import com.zzyl.nursing.vo.CheckInDetailVo;
import com.zzyl.nursing.vo.CheckInElderVo;
import com.zzyl.nursing.vo.ElderFamilyVo;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.zzyl.nursing.mapper.CheckInMapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import java.util.Arrays;
/**
 * 入住Service业务层处理
 * 
 * @author ruoyi
 * @date 2024-12-26
 */
@Service
@RequiredArgsConstructor
public class CheckInServiceImpl extends ServiceImpl<CheckInMapper,CheckIn> implements ICheckInService
{

    private final CheckInMapper checkInMapper;
    private final IElderService elderService;
    private final IBedService bedService;
    private final ICheckInConfigService checkInConfigService;
    private final IContractService contractService;
    private final CheckInConfigMapper checkInConfigMapper;
    private final ContractMapper contractMapper;

    private  static  final int BED_STATUS_USED = 1;
    private static  final int BED_STATUS_USEDD = 4;

    /**
     * 查询入住
     * 
     * @param id 入住主键
     * @return 入住
     */
    @Override
    public CheckIn selectCheckInById(Long id)
    {
        return getById(id);
    }

    /**
     * 查询入住列表
     * 
     * @param checkIn 入住
     * @return 入住
     */
    @Override
    public List<CheckIn> selectCheckInList(CheckIn checkIn)
    {
        return checkInMapper.selectCheckInList(checkIn);
    }




    /**
     * 新增入住
     * @param  checkInApplyDto 入住
     * @return 结果
     */
    @Override
    @Transactional
    public void apply(CheckInApplyDto checkInApplyDto) {
        //业务逻辑
        //1.校验老人是否已经入住 2.修改床位状态更改为已入住 3.插入相关表四张
        //获取身份证 根据身份证查询老人表
        String idCardNo = checkInApplyDto.getCheckInElderDto().getIdCardNo();
        LambdaQueryWrapper<Elder> elderLambdaQueryWrapper = new LambdaQueryWrapper<>();
        elderLambdaQueryWrapper.eq(Elder::getIdCardNo,idCardNo);
        Elder elder = elderService.getOne(elderLambdaQueryWrapper);
        if ( elder !=null){
            throw new BaseException("该老人已经入住");
        }
        //更新床位状态
        Bed bed = bedService.getById(checkInApplyDto.getCheckInConfigDto().getBedId());
        bed.setBedStatus(BED_STATUS_USED);
        bedService.updateById(bed);
        //新增老人表
        elder = saveElder(checkInApplyDto, bed);
        //新增入住表
        CheckIn checkIn = saveCheckin(checkInApplyDto, elder, bed);
        //新增入住配置表
        saveCheckinConfig(checkIn.getId(),checkInApplyDto);
        //新增合同表
        saveContract(checkInApplyDto,elder);



    }


    //新增合同表
    private void saveContract(CheckInApplyDto checkInApplyDto, Elder elder) {
        Contract contract = new Contract();
        BeanUtils.copyProperties(checkInApplyDto.getCheckInContractDto(),contract);
        //设置老人信息
        contract.setElderId(elder.getId());
        contract.setElderName(elder.getName());
        contract.setContractNumber(CodeGenerator.generateContractNumber());//合同编号
        LocalDateTime startDate = checkInApplyDto.getCheckInConfigDto().getStartDate();
        LocalDateTime endDate = checkInApplyDto.getCheckInConfigDto().getEndDate();
        contract.setStartDate(startDate);
        contract.setEndDate(endDate);
        //如果当前日期小于startDate，表示合同未生效
        if (LocalDateTime.now().isBefore(startDate)){
            contract.setStatus(0);
        }else{
            contract.setStatus(1);
        }

        contractService.save(contract);

    }

    //新增入住配置表
    private void saveCheckinConfig(Long checkId, CheckInApplyDto checkInApplyDto) {
        CheckInConfig checkInConfig = new CheckInConfig();
        BeanUtils.copyProperties(checkInApplyDto.getCheckInConfigDto(), checkInConfig);
        checkInConfig.setCheckInId(checkId);
        checkInConfigService.save(checkInConfig);

    }

    //新增入住信息
    private CheckIn saveCheckin(CheckInApplyDto checkInApplyDto, Elder elder, Bed bed) {

        CheckIn checkIn = new CheckIn();
        checkIn.setElderName(elder.getName());
        checkIn.setElderId(elder.getId());
        checkIn.setIdCardNo(elder.getIdCardNo());
        CheckInConfigDto config = checkInApplyDto.getCheckInConfigDto();
        checkIn.setStartDate(config.getStartDate()); //入住开始时间
        checkIn.setEndDate(config.getEndDate());  //入住结束时间
        checkIn.setNursingLevelName(config.getNursingLevelName());
        checkIn.setBedNumber(bed.getBedNumber());

        //新增家属信息
        List<ElderFamilyDto> elderFamilyDtoList = checkInApplyDto.getElderFamilyDtoList();
        checkIn.setRemark(JSONUtil.toJsonStr(elderFamilyDtoList));
        super.save(checkIn);
        return checkIn;
    }

    //新增老人表
    private Elder saveElder(CheckInApplyDto checkInApplyDto ,Bed bed) {
        Elder elder = new Elder();
        BeanUtils.copyProperties(checkInApplyDto.getCheckInElderDto(), elder);
        elder.setStatus(BED_STATUS_USEDD);
        elder.setBedId(bed.getId());
        elder.setBedNumber(bed.getBedNumber());
        elderService.save(elder);
        return  elder;
    }


    /**
     * 修改入住
     * 
     * @param checkIn 入住
     * @return 结果
     */
    @Override
    public int updateCheckIn(CheckIn checkIn )
    {
        return updateById(checkIn)?1:0;
    }

    /**
     * 批量删除入住
     * 
     * @param ids 需要删除的入住主键
     * @return 结果
     */
    @Override
    public int deleteCheckInByIds(Long[] ids)
    {
        return removeByIds(Arrays.asList(ids))?1:0;
    }

    /**
     * 删除入住信息
     * 
     * @param id 入住主键
     * @return 结果
     */
    @Override
    public int deleteCheckInById(Long id)
    {
        return removeById(id)?1:0;
    }



    //查询入住详情
    @Override
    public CheckInDetailVo detail(Long id) {
        //封装返回入住详情
        CheckInDetailVo checkInDetailVo = new CheckInDetailVo();
        CheckIn checkIn = checkInMapper.selectById(id);
        if(checkIn == null){
            throw new BaseException("找不到入住信息");
        }
        //获取老人信息
        Long elderId = checkIn.getElderId();
        Elder elder = elderService.selectElderById(elderId);

        CheckInElderVo checkInElderVo = new CheckInElderVo();
        BeanUtils.copyProperties(elder,checkInElderVo);
        //计算年龄，因为数据没有存
        LocalDate birthDay = LocalDate.parse(elder.getBirthday());
        checkInElderVo.setAge(LocalDateTime.now().getYear() - birthDay.getYear());
        checkInDetailVo.setCheckInElderVo(checkInElderVo);

        //封装家属信息，将JSON转换为集合
        if(StringUtils.hasText(checkIn.getRemark())){
            List<ElderFamilyVo> elderFamilyVoList = JSONUtil.parseArray(checkIn.getRemark()).toList(ElderFamilyVo.class);
            checkInDetailVo.setElderFamilyVoList(elderFamilyVoList);
        }else{
            //没有家庭成员信息返回 前端会报错，这里做一下兼容
            checkInDetailVo.setElderFamilyVoList(new ArrayList<>());
        }
        //封装入住配置
        CheckInConfig checkInConfig = checkInConfigMapper.selectOne(Wrappers.<CheckInConfig>lambdaQuery().eq(CheckInConfig::getCheckInId, checkIn.getId()));
        CheckInConfigVo checkInConfigVo = new CheckInConfigVo();
        BeanUtils.copyProperties(checkInConfig,checkInConfigVo);
        //设置入住开始结束时间，测试发现没有回显才知道这里需要单独设置的
        checkInConfigVo.setStartDate(checkIn.getStartDate());
        checkInConfigVo.setEndDate(checkIn.getEndDate());
        checkInDetailVo.setCheckInConfigVo(checkInConfigVo);

        //封装合同信息
        Contract contract = contractMapper.selectOne(Wrappers.<Contract>lambdaQuery().eq(Contract::getElderId, elderId));
        checkInDetailVo.setContract(contract);

        return checkInDetailVo;
    }

}
